package edu.hunau.cxb19.oop.class25;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import org.junit.Test;

/**
 *
 * @author hb
 *
 *         2020-03-30 14:52:50
 */
public class FileTest {

	@Test
	public void fileTest() {
		// 获得当前目录的File实例
		File file = new File(".");
		// 在当前的工程中
		System.out.println(file.getAbsolutePath());

		// 在当前目录下创建一个子目录 demo
		File demo = new File(file, "demo");
		System.out.println(demo.exists());
		demo.mkdir();

		File dir = new File(".\\demo\\dir01\\dir02");
		if (!dir.exists()) {
			dir.mkdirs();
		}
	}

	@Test
	public void createFileTest() throws Exception {
		File demo = new File(".\\demo");
		File a01 = new File(demo, "a01.txt");
		if (!a01.exists()) {
			a01.createNewFile();
		}

		File a02 = new File(".\\demo\\a02.txt");
		if (!a02.exists()) {
			a02.createNewFile();
		}
	}

	@Test
	public void renameToTest() {
		File src = new File(".\\demo\\a01.txt");
		File dest = new File(".\\demo\\demo01.txt");
		src.renameTo(dest);
	}

	@Test
	public void deleteDir() {
		File dir01 = new File("./demo/dir01/dir02");
		boolean flag = dir01.delete();
		System.out.println(flag);
	}

	@Test
	public void tempFileTest() throws Exception {
		File dest = new File(".\\demo");
		File f1 = File.createTempFile("temp", ".txt", dest);
		// 临时文件会在程序退出时删除
		f1.deleteOnExit();
	}

	@Test
	public void listTest() {
		File demo = new File(".\\demo");
		String[] fileNames = demo.list();
		// [a02.txt, demo01.txt, dir01]
		System.out.println(Arrays.toString(fileNames));

		File[] files = demo.listFiles();
		// [.\demo\a02.txt, .\demo\demo01.txt, .\demo\dir01]
		System.out.println(Arrays.toString(files));
	}

	@Test
	public void filterTest() {
		File demo = new File(".\\demo");
		String[] txts = demo.list((dir, name) -> name.endsWith(".txt"));
		System.out.println(Arrays.toString(txts));

		File[] fileTxts = demo.listFiles(f -> f.getName().endsWith(".txt"));
		System.out.println(Arrays.toString(fileTxts));
	}
	
	@Test
	public void listAllTest() {
		File demo = new File("C:\\Windows\\System32");
		List<File> files = listAll(demo, ".txt");
		files.forEach(System.out::println);
	}

	public List<File> listAll(File dir, String ext) {
		List<File> list = new ArrayList<File>();
		// 获得dir中符合条件的文件
		File[] files = dir.listFiles(f -> f.getName().endsWith(ext));
		if (Objects.nonNull(files) && files.length > 0) {
			list.addAll(Arrays.asList(files));
		}

		// 获得dir中所有的子目录
		File[] subDirs = dir.listFiles(f -> f.isDirectory());
		if(Objects.nonNull(subDirs)&& subDirs.length>0) {
			for (File sub : subDirs) {
				list.addAll(listAll(sub,ext));
			}
		}
		return list;
	}
}
